package com.yzk.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yzk.train.business.entity.TrainStation;
import com.yzk.train.business.entity.TrainStationExample;
import com.yzk.train.business.mapper.TrainStationMapper;
import com.yzk.train.business.request.TrainStationQueryReq;
import com.yzk.train.business.request.TrainStationSaveReq;
import com.yzk.train.business.response.TrainStationQueryResp;
import com.yzk.train.common.exception.BusinessException;
import com.yzk.train.common.exception.ExceptionEnum;
import com.yzk.train.common.response.PageResp;
import com.yzk.train.common.utils.SnowUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TrainStationService {

    @Resource
    private TrainStationMapper trainStationMapper;

    /**
     * 保存 / 更新 停靠站
     * @param req
     */
    public String save(TrainStationSaveReq req) {
        TrainStation trainStation = BeanUtil.copyProperties(req, TrainStation.class);
        DateTime now = DateTime.now();
        trainStation.setUpdateTime(now);
        if (ObjectUtil.isNull(trainStation.getId())) {

            // 保存之前，先校验唯一键是否存在，车次编号 - 站序
            TrainStation trainStationDB = selectByUnique(req.getTrainCode(), req.getIndex());
            if (ObjectUtil.isNotEmpty(trainStationDB)) {
                throw new BusinessException(ExceptionEnum.BUSINESS_TRAIN_STATION_INDEX_UNIQUE_ERROR);
            }
            // 保存之前，先校验唯一键是否存在，车次编号 - 站名
            trainStationDB = selectByUnique(req.getTrainCode(), req.getName());
            if (ObjectUtil.isNotEmpty(trainStationDB)) {
                throw new BusinessException(ExceptionEnum.BUSINESS_TRAIN_STATION_NAME_UNIQUE_ERROR);
            }

            trainStation.setId(SnowUtil.getSnowflakeNextId());
            trainStation.setCreateTime(now);
            trainStationMapper.insert(trainStation);
            return "保存成功";
        } else {
            trainStationMapper.updateByPrimaryKey(trainStation);
            return "编辑成功";
        }
    }

    /**
     * 查询 停靠站
     * @param req
     */
    public PageResp<TrainStationQueryResp> queryList(TrainStationQueryReq req) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.setOrderByClause("train_code asc, `index` asc");
        // 如果有车次编号，则按照车次编码查询
        if (ObjectUtil.isNotNull(req.getTrainCode())) {
            trainStationExample.createCriteria().andTrainCodeEqualTo(req.getTrainCode());
        }
        // 使用分页插件
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<TrainStation> trainStations = trainStationMapper.selectByExample(trainStationExample);
        // 使用 PageInfo 包装查询结果
        PageInfo<TrainStation> pageInfo = new PageInfo<>(trainStations);
        // 转换为 PageResp
        List<TrainStationQueryResp> list = BeanUtil.copyToList(trainStations, TrainStationQueryResp.class);
        return new PageResp<>(pageInfo.getTotal(), list);
    }

    /**
     * 根据ID删除停靠站
     * @param id
     */
    public void delete(Long id) {
        trainStationMapper.deleteByPrimaryKey(id);
    }

    /**
     * 校验唯一键
     * @param trainCode 车次编码
     * @param index     站序
     * @return
     */
    private TrainStation selectByUnique(String trainCode, Integer index) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andIndexEqualTo(index);
        List<TrainStation> list = trainStationMapper.selectByExample(trainStationExample);
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 校验唯一键
     * @param trainCode 车次编码
     * @param name      站名
     * @return
     */
    private TrainStation selectByUnique(String trainCode, String name) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andNameEqualTo(name);
        List<TrainStation> list = trainStationMapper.selectByExample(trainStationExample);
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 根据车次编号查询车次站点信息
     *
     * @param trainCode
     * @return
     */
    public List<TrainStation> selectByTrainCode(String trainCode) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.setOrderByClause("`index` asc");
        trainStationExample.createCriteria().andTrainCodeEqualTo(trainCode);
        return trainStationMapper.selectByExample(trainStationExample);
    }

}
